import React, {useEffect, useState} from 'react';
import {Building2, ChevronDown, ChevronRight, Search, X} from 'lucide-react';
import {Req} from "../../util/fetch.ts";

interface Medal {
  id: number;
  name: string;
  icon: string;
  grantedUsers: any;
}

interface User {
  id: number;
  realname: string;
  avatarUrl: string;
  position: string;
}

interface Department {
  id: number;
  name: string;
  children?: Department[];
  users?: User[];
}

interface MedalGrantModalProps {
  medal: Medal;
  onClose: () => void;
  onSave: (users: User[]) => void;
}

export default function MedalGrantModal({
  medal,
  onClose,
  onSave
}: MedalGrantModalProps) {
  const [searchTerm, setSearchTerm] = useState('');
  const [treeList, setTreeList] = useState([]);
  const [selectedUsers, setSelectedUsers] = useState<User[]>([]);
  const [expandedDepts, setExpandedDepts] = useState<number[]>([]);

  const toggleDepartment = (deptId: number) => {
    setExpandedDepts(prev =>
      prev.includes(deptId)
        ? prev.filter(id => id !== deptId)
        : [...prev, deptId]
    );
  };

  const getAllUsersInDept = (dept: Department): User[] => {
    let users: User[] = [];
    if (dept.users) {
      users = [...dept.users];
    }
    if (dept.children) {
      dept.children.forEach(child => {
        users = [...users, ...getAllUsersInDept(child)];
      });
    }
    return users;
  };

  const toggleUser = (user: User) => {
    setSelectedUsers(prev =>
      prev.some(u => u.id === user.id)
        ? prev.filter(u => u.id !== user.id)
        : [...prev, user]
    );
  };

  const isUserSelected = (userId: number) => {
    return selectedUsers.some(u => u.id === userId);
  };

  const handleSubmit = () => {
    onSave(selectedUsers);
  };

  const queryAreaTree = async () => {
    const res = await Req('/bsArea/tree');
    setTreeList(res.data);
  }

  useEffect(() => {
    queryAreaTree()
    setSelectedUsers(medal.grantedUsers ? medal.grantedUsers : [])
  }, []);

  // 递归渲染部门树
  const renderDepartment = (dept: Department, level = 0) => {
    const isExpanded = expandedDepts.includes(dept.id);

    return (
      <div key={dept.id} className="select-none">
        <div 
          className={`flex items-center py-2 px-3 rounded-lg hover:bg-gray-50
            ${level > 0 ? 'ml-6' : ''}`}
        >
          {(dept.children?.length || dept.users?.length) > 0 ? (
            <button
              onClick={() => toggleDepartment(dept.id)}
              className="p-1 hover:bg-gray-200 rounded"
            >
              {isExpanded ? (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronRight className="w-4 h-4 text-gray-500" />
              )}
            </button>
          ) : (
            <span className="w-6" />
          )}
          
          <div className="flex items-center flex-1">
            <Building2 className="w-5 h-5 mr-2 text-gray-400" />
            <span className="font-medium">{dept.name}</span>
          </div>
        </div>

        {isExpanded && (
          <div>
            {dept.children?.map(child => renderDepartment(child, level + 1))}
            {dept.users?.map(user => (
              <div
                key={user.id}
                className={`flex items-center py-2 px-3 ml-6 rounded-lg hover:bg-gray-50`}
              >
                <span className="w-6" />
                <div className="flex items-center flex-1">
                  <input
                    type="checkbox"
                    checked={isUserSelected(user.id)}
                    onChange={() => toggleUser(user)}
                    className="w-4 h-4 mr-3 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                  />
                  <img
                      src={user.avatarUrl}
                    className="w-8 h-8 rounded-full mr-2"
                  />
                  <div>
                    <div className="font-medium text-gray-900">
                      {user.realname}
                    </div>
                    <div className="text-sm text-gray-500">
                      {user.position}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
      <div className="bg-white rounded-lg w-full max-w-6xl mx-4 max-h-[90vh] flex flex-col">
        <div className="flex items-center justify-between p-4 border-b">
          <div className="flex items-center space-x-3">
            <span className="text-2xl">{medal.icon}</span>
            <h3 className="text-lg font-semibold text-gray-900">
              发放 {medal.name} 勋章
            </h3>
          </div>
          <button onClick={onClose}>
            <X className="w-6 h-6 text-gray-500" />
          </button>
        </div>

        <div className="p-4 border-b">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
            <input
              type="text"
              placeholder="搜索用户..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
        </div>

        <div className="flex-1 flex overflow-hidden">
          {/* 左侧部门树 */}
          <div className="w-1/2 border-r overflow-y-auto p-4">
            {treeList.map(dept => renderDepartment(dept))}
          </div>

          {/* 右侧已选人员列表 */}
          <div className="w-1/2 overflow-y-auto p-4">
            <div className="mb-4">
              <h4 className="text-lg font-medium text-gray-900">
                已选择人员 ({selectedUsers.length})
              </h4>
            </div>
            <div className="space-y-2">
              {selectedUsers.map(user => (
                <div
                  key={user.id}
                  className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
                >
                  <div className="flex items-center">
                    <img
                        src={user.avatarUrl}
                      className="w-8 h-8 rounded-full mr-3"
                    />
                    <div>
                      <div className="font-medium text-gray-900">
                        {user.realname}
                      </div>
                      <div className="text-sm text-gray-500">
                        {user.position}
                      </div>
                    </div>
                  </div>
                  <button
                    onClick={() => toggleUser(user)}
                    className="p-1 text-gray-400 hover:text-red-500"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="flex justify-between items-center p-4 bg-gray-50 rounded-b-lg">
          <div className="text-sm text-gray-600">
            已选择 {selectedUsers.length} 人
          </div>
          <div className="space-x-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
            >
              取消
            </button>
            <button
              onClick={handleSubmit}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
            >
              确认发放
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}